﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ThemeText.Models
{
    sealed public class ThemeFilterViewAttribute : ActionFilterAttribute
    {
        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            var viewResult = filterContext.Result as ViewResult;
            if (viewResult != null)
            {
                var template = "Default";
                if (filterContext.RequestContext.HttpContext.Session != null)
                {
                    var sessionTemplate = filterContext.RequestContext.HttpContext.Session["template"];
                    if (sessionTemplate != null) template = sessionTemplate.ToString();
                }
                //var template = string.IsNullOrEmpty(currentUserTemplate) ? TemplateService.DefaultTemplateName : currentUserTemplate;

                //var controller = filterContext.RequestContext.RouteData.Values["Controller"].ToString();
                //var action = filterContext.RequestContext.RouteData.Values["Action"].ToString();

                var routeData = filterContext.RequestContext.RouteData;
                var controllerName = routeData.GetRequiredString("controller");
                var actionName = routeData.GetRequiredString("action");
                var areaName = routeData.DataTokens["area"] ?? null;

                string normalPath, tempPath;
                if (areaName == null)
                {
                    normalPath = "~/Views/" + controllerName + "/" + actionName + ".cshtml";
                    tempPath = "~/Theme/" + template + "/Views/" + controllerName + "/" + actionName + ".cshtml";
                }
                else
                {
                    normalPath = "~/Areas/" + areaName + "/Views/" + controllerName + "/" + actionName + ".cshtml";
                    tempPath = "~/Areas/" + areaName + "/Theme/" + template + "/Views/" + controllerName + "/" + actionName + ".cshtml";
                }

                var viewPath = normalPath;
                var server = filterContext.RequestContext.HttpContext.Server;
                if (System.IO.File.Exists(server.MapPath(tempPath)))
                    viewPath = tempPath;

                viewResult.ViewName = viewPath;

                //if (string.IsNullOrWhiteSpace(viewResult.ViewName))
                //{
                //    viewResult.ViewName = string.Format(
                //        "~/Views/{0}/{1}/{2}/{3}.{4}",
                //        TemplateService.TemplateDirectoryName,
                //        template,
                //        controller,
                //        action,
                //        TemplateService.TemplateFileExtension);

                //    return;
                //}
            }

            base.OnResultExecuting(filterContext);
        }

    }
}